var express = require('express')
var router = express.Router()
const Food = require('../db/model/foodModel')
// 添加商品
router.post('/add', (req, res) => {
  const {name, price, desc, typename, typeid, img} = req.body
  console.log(name, price, desc, typename, typeid, img)
  if (name && price && desc && typename && typeid && img) {
    Food.insertMany({name, price, desc, typename, typeid, img})
      .then(resdata => {
        res.send({msg: '添加成功！', status: 1})
      })
      .catch(err => {
        console.log(err)
        res.send({msg: '添加失败！', status: 0})
      })
  } else {
    res.send({msg: '添加失败,参数错误！', status: 0})
  }
})
// 通过typename查询不同类型的商品
router.post('/getlistsByname', (req, res) => {
  const {typename} = req.body
  Food.find({typename})
    .then(resdata => {
      console.log(resdata)
      res.send({msg: '查询成功', status: 1, lists: resdata})
    })
    .catch(err => {
      console.log(err)
      res.send({msg: '列表获取失败！', status: 0})
    })
})
// 获取所有商品
router.get('/getLists', (req, res) => {
  Food.find()
    .then(resdata => {
      console.log(resdata)
      res.send({msg: '查询成功', status: 1, data: resdata})
    })
    .catch(err => {
      console.log(err)
      res.send({msg: '列表获取失败！', status: 0})
    })
})
// 通过_id删除商品
router.post('/del', (req, res) => {
  const {_id} = req.body
  Food.deleteMany({_id})
    .then(resdata => {
      console.log(resdata)
      res.send({msg: '删除成功', status: 1})
    })
    .catch(err => {
      console.log(err)
      res.send({msg: '删除失败！', status: 0})
    })
})
// 修改商品
router.post('/updateLists', (req, res) => {
  const {name, price, desc, typename, typeid, img, _id} = req.body
  if (name && price && desc && typename && typeid && img && _id) {
    Food.updateOne({_id}, {name, price, desc, typename, typeid, img})
      .then(resdata => {
        res.send({msg: '修改成功！', status: 1})
      })
      .catch(err => {
        console.log(err)
        res.send({msg: '修改失败！', status: 0})
      })
  } else {
    res.send({msg: '参数错误！！', status: 0})
  }
})
module.exports = router
